import os
import django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", 'IPTVOPlatform.settings')
django.setup()
from oplatform.models import ChannelData

path = '/var/www/channels.txt'
all_channels = []


def clean_channel():
    ChannelData.objects.all().delete()


def create_channel(path):
    file = open(path, 'r')
    flag = True
    id = 1
    while flag:
        line = file.readline()
        if line != '':
            channel_split = line.split(':')
            name = channel_split[0]
            provider_name = channel_split[1]
            coderate = channel_split[2]
            freq = channel_split[3]
            modulation = channel_split[4]
            delivery_system = channel_split[5]
            srate = channel_split[6]
            sid = channel_split[7]
            pmt = channel_split[8]
            pcr = channel_split[9]
            video_id = channel_split[10]
            audio_id = channel_split[11]
            subtitle = channel_split[12]
            caid = channel_split[13]
            print(file.readline())
            channel_item = {
                'id': id,
                'name': name,
                'provider_name': provider_name,
                'coderate': coderate,
                'freq': freq,
                'modulation': modulation,
                'delivery_system': delivery_system,
                'srate': srate,
                'sid': sid,
                'pmt': pmt,
                'pcr': pcr,
                'video_id': video_id,
                'audio_id': audio_id,
                'subtitle': subtitle,
                'caid': caid,
            }
            all_channels.append(channel_item)
            id += 1
            print(id)
        else:
            for channel in all_channels:
                ChannelData.objects.get_or_create(
                    id=channel.get('id'),
                    name=channel.get('name'),
                    provider_name=channel.get('provider_name'),
                    coderate=channel.get('coderate'),
                    freq=channel.get('freq'),
                    modulation=channel.get('modulation'),
                    delivery_system=channel.get('delivery_system'),
                    srate=channel.get('srate'),
                    sid=channel.get('sid'),
                    pmt=channel.get('pmt'),
                    pcr=channel.get('pcr'),
                    video_id=channel.get('video_id'),
                    audio_id=channel.get('audio_id'),
                    subtitle=channel.get('subtitle'),
                    caid=channel.get('caid'),
                )
            flag = False


def run():
    clean_channel()
    create_channel(path)
    print('success')


run()
